﻿using System;
using System.Collections.Generic;
using System.Text;

namespace ArgusLib.Controls
{
	public class NumericTextBox<T> : TextBox
	{
		protected ValueChecker<T> ValueChecker { get; private set; }

		public T Value { get { return this.ValueChecker.Value; } set { this.ValueChecker.Value = value; } }

		public NumericTextBox()
			: base()
		{
			this.ValueChecker = new ValueChecker<T>(this, null);
			this.ValueChecker.AllowedChars = this.GetAllowedChars();
		}

		protected virtual IEnumerable<CharSet> GetAllowedChars()
		{
			return null;
		}

		//protected override void OnKeyUp(System.Windows.Forms.KeyEventArgs e)
		//{
		//	base.OnKeyUp(e);

		//	if (e.KeyCode == System.Windows.Forms.Keys.Enter == this.ValueChecker.CurrentTextIsValid == false)
		//	{
		//		this.Text = this.ValueChecker.LastValidText;
		//		this.SelectionStart = this.Text.Length;
		//	}
		//}

		//protected override void OnLostFocus(EventArgs e)
		//{
		//	base.OnLostFocus(e);

		//	if (this.ValueChecker.CurrentTextIsValid == false)
		//		this.Text = this.ValueChecker.LastValidText;
		//}

		public event EventHandler ValueChanged
		{
			add { this.ValueChecker.ValueChanged += value; }
			remove { this.ValueChecker.ValueChanged -= value; }
		}

		public new event EventHandler TextChanged
		{
			add { this.ValueChecker.TextChanged += value; }
			remove { this.ValueChecker.TextChanged -= value; }
		}
#if false
		protected abstract CharSet[] GetAllowedChars();
		protected abstract bool ValidateText(string text, out T value);

		public T Value { get; private set; }

		string lastValidatedText;

		public NumericTextBox()
			: base()
		{
			this.AllowedChars = this.GetAllowedChars();
		}

		protected override void OnTextChanged(EventArgs e)
		{
			T value;
			if (this.ValidateText(this.Text, out value) == true)
			{
				this.lastValidatedText = this.Text;
				this.Value = value;
			}
			base.OnTextChanged(e);
		}

		protected override void OnKeyUp(System.Windows.Forms.KeyEventArgs e)
		{
			base.OnKeyUp(e);

			if (e.KeyCode == System.Windows.Forms.Keys.Enter)
			{
				this.Text = this.lastValidatedText;
				this.SelectionStart = this.lastValidatedText.Length;
			}
		}

		protected override void OnLostFocus(EventArgs e)
		{
			base.OnLostFocus(e);

			this.Text = this.lastValidatedText;
		}
#endif
	}
}
